package com.wuhunyu.security;

import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.servicebase.result.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出登录管理
 * @author wuhunyu
 */
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;

    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("wuhunyu_token");
        if (Check.isNotBlank(token)) {
            // 删除redis中的token
            redisTemplate.delete(tokenManager.getUserFromToken(token));
        }
        ResponseUtil.out(response, CommonResult.success("退出登录成功"));
    }

}